package netty.test22TcpSelfProto;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * ##########################
 *
 * 每一个通道的 handler都是独立的，都有自己的相互不影响
 *
 *
 */
public class MySPServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count=0;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务端接收的信息如下。。。。");
        System.out.println("长度 len="+len);
        System.out.println("内容 content="+new String(content,CharsetUtil.UTF_8));
        System.out.println("服务器接收到消息数量 "+(++this.count));
        System.out.println("###############################");

        //服务器端给客户端回送的消息
        String response="服务器端给客户端回送的消息";
        int leng=response.getBytes(StandardCharsets.UTF_8).length;
        //构建回复协议包
        MessageProtocol message = new MessageProtocol();
        message.setLen(leng);
        message.setContent(response.getBytes(StandardCharsets.UTF_8));
        channelHandlerContext.writeAndFlush(message);


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
